import 'package:flutter/material.dart';
import 'package:flutter_base/pages/test_detail/model/model_test_detail.dart';
import 'package:flutter_base/user/app_user_manager.dart';
import 'package:flutter_base/utils/log/utils_log.dart';
import 'package:get/get.dart';
import 'package:flutter_base/base/controller/base_controller.dart';
import 'package:flutter_base/http/http_export.dart';

class TestDetailLogic extends BaseController {
  // 测试ID
  final int testId =  Get.arguments?['testId'] ?? 0;

  // 测试详情数据
  var testDetail = Rx<ModelTestDetail>(ModelTestDetail());

  // 收藏状态
  // final RxBool isFavorite = false.obs;

  final RxInt currentGrowthStage = 3.obs;


  // 滚动相关变量
  final ScrollController scrollController = ScrollController();
  final RxDouble scrollPosition = 0.0.obs;
  final RxBool isDarkTitle = true.obs;

  // 计算AppBar背景透明度 (0-1)
  double get appBarOpacity => (scrollPosition.value / 100).clamp(0.0, 1.0);

  @override
  void onInit() {
    super.onInit();
    // 初始化滚动控制器
    scrollController.addListener(_onScroll);
  }

  // 滚动监听函数
  void _onScroll() {
    scrollPosition.value = scrollController.offset;
    // 更新标题颜色状态（滚动超过50时变为深色）
    isDarkTitle.value = scrollController.offset <= 50;
  }

  @override
  void onReady() {
    super.onReady();
    // 加载测试详情数据
    // loadTestDetail();
    executeInitMethod(loadTestDetail);
  }

  @override
  void onClose() {
    // 释放滚动控制器
    scrollController.removeListener(_onScroll);
    scrollController.dispose();
    super.onClose();
  }

  // 加载测试详情
  Future<void> loadTestDetail() async {
    // doLoading();

    // try {
    // 使用 HTTP 请求获取测试详情
    HttpResponse response = await HttpManager().get(API.psychologyDetail,
        params: {'id': testId},
        uiType: HttpUIType.toast, // 因为已经在页面上显示了加载状态
        fromJson: ModelTestDetail.fromJson);

    if (response.isSuccess) {
      testDetail.value = response.data;
      // testDetail.value.questions!.first.type = 9;
      // testDetail.value.questions![1].type = 10;
      // 设置收藏状态
      // if (testDetail.value.isFavorite != null) {
      //   isFavorite.value = testDetail.value.isFavorite!;
      // }
    } else {
      doError('获取测试详情失败');
    }
  }

  // 添加收藏
  Future<void> addFavorite() async {
    // if (testId == null) return;
    clog('message   ${AppUserManager().token}');
    HttpResponse response = await HttpManager().post(
      API.favoriteAdd,
      params: {'test_id': testId},
      uiType: HttpUIType.loadingAndToast,
    );

    if (response.isSuccess) {
      // isFavorite.value = true;
      // 更新测试详情中的收藏状态
      testDetail.update((val) {
        val?.isFavorite = true;
      });
    }
  }

  // 取消收藏
  Future<void> removeFavorite() async {
    HttpResponse response = await HttpManager().post(
      API.favoriteRemove,
      params: {'test_id': testId},
      uiType: HttpUIType.loadingAndToast,
    );

    if (response.isSuccess) {
      // isFavorite.value = false;
      // 更新测试详情中的收藏状态
      testDetail.update((val) {
        val?.isFavorite = false;
      });
    }
  }

  // 切换收藏状态
  Future<void> toggleFavorite() async {
    if (testDetail.value.isFavorite == true) {
      await removeFavorite();
    } else {
      await addFavorite();
    }
  }

  // 开始测试
  Future<void> startTest() async {

    HttpResponse response = await HttpManager().post(
      API.testStart,
      params: {'test_id': testId},
      uiType: HttpUIType.loadingAndToast,
    );
    if (response.isSuccess) {
      // 测试开始成功，跳转到问题页面user_test_id
      Get.toNamed('/test/questions', arguments: {
        'testId': testId,
        'testDetail': testDetail.value,
        'userTestId': response.data['user_test_id']
      });
    }
  }
}
